我已经使用owin登录但无法退出.
在开始:
public void ConfigureOAuth(IAppBuilder app)
{
OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions()
{
AllowInsecureHttp = true,
TokenEndpointPath = new PathString("/token"),
AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(20),
Provider = new AuthorizationServerProvider(),
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie
};
app.UseOAuthBearerTokens(OAuthServerOptions);
app.UseCookieAuthentication(new CookieAuthenticationOptions());
}
在AuthorizationServerProvider中:
public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
{
context.Validated();
return Task.FromResult(null);
}
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*"});
using (demoEntities _repo = new demoEntities())
{
if (!_repo.users.Where(x => x.username == context.UserName && x.pass == context.Password).Any())
{
context.SetError("invalid_grant", "wrong.");
//context.Rejected();
return;
} … 我有一个C#WebApi项目,并且正在使用FluentValidation.WebApi包来验证客户端输入。
下面是我的模型类代码,它具有名为“ IsPremium”的C#属性。对于所有客户端,此属性均具有json名称“ isLuxury”。
[Serializable, JsonObject, Validator(typeof(ProductValidator))]
public class Product
{
[JsonProperty("isLuxury")]
public bool? IsPremium { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
我的验证器类如下所示:
public class ProductValidator : AbstractValidator<Product>
{
public ProductValidator()
{
RuleFor(product => product.isPremium).NotNull();
}
}
Run Code Online (Sandbox Code Playgroud)
所以对于这样的请求: http:// localhost:52664 / api / product
请求正文:{“ isLuxury”:“”}
我收到以下错误:
{
"Message": "The request is invalid.",
"ModelState": {
"product.isPremium": [
"'is Premium' must not be empty."
]
}
}
Run Code Online (Sandbox Code Playgroud)
流利的选择了C#属性名称,这对客户端没有意义,因为它知道它是“ isLuxury”。如何强制Fluent从json属性而不是c#属性中选择名称,以提供更好的验证,例如“'isLuxury'不能为空。”?
如果不可能的话,我将不得不重命名我所有的C#属性,使其具有与公开给所有客户端的json相同的名称。请提出您是否还有其他更好的方法来解决此问题。
我有ChangePassword方法,我必须User.Identity.GetUserId()找到UserId.
问题:它总是返回null.不明白为什么.
我在另一篇文章中读到了GetUserById使用下面的代码行查找Id.我不知道如何嘲笑ClaimsTypes.NameIdentifier.
return ci.FindFirstValue(ClaimTypes.NameIdentifier);
ChangePassword方法(单位测试的方法)
public async Task<IHttpActionResult> ChangePassword(string NewPassword, string OldPassword)
{
_tstService = new TestService();
IdentityResult result = await _tstService.ChangePassword(User.Identity.GetUserId(), OldPassword, NewPassword);
if (!result.Succeeded)
{
return GetErrorResult(result);
}
return Ok();
}
Run Code Online (Sandbox Code Playgroud)
单元测试
var mock = new Mock<MyController>();
mock.CallBase = true;
var obj = mock.Object;
obj.ControllerContext = new HttpControllerContext { Request = new HttpRequestMessage() };
obj.Request.SetOwinContext(CommonCodeHelper.mockOwinContext());
IPrincipal user = GetPrincipal();
obj.ControllerContext.RequestContext.Principal = user;
var result = …Run Code Online (Sandbox Code Playgroud) 检查WebAPI是否可用的最佳方法是什么?我想在一个简单的if()声明中检查它,是否可以保持它相对简单?如果有更好的方法来检查.像一个尝试/捕获.就告诉我嘛.谢谢
我想在我的代码隐藏Page_Load方法中包含if语句.因此,当API不可用时,我可以阻止该网站.
我试过这个:
try
{
WebClient client = new WebClient();
client.UseDefaultCredentials = true;
string response = client.DownloadString(baseuri + Constants.API_LEHRLING + lehrlingID);
}
catch (Exception ex)
{
string url = "AccessDenied.aspx";
Server.Transfer(url, true);
}
Run Code Online (Sandbox Code Playgroud)
我想从我的webapi下载一个字符串.我的uri是自动构建的.如果发生异常,我会参考我的错误网站.
还有其他想法吗?这种方法有效,但不是很干净
我目前正在使用WebApiRequestLifestyle具有默认的范围生活方式.我想在OWIN中间件和其中一个API控制器中注入一个服务,服务的范围应该仍然是WebAPI,即对于整个请求,应该只有一个服务实例.
public class TestMiddleware : OwinMiddleware
{
private readonly ITestService _testService;
public TestMiddleware(OwinMiddleware next, ITestService testService) : base(next)
{
_testService = testService;
}
public override async Task Invoke(IOwinContext context)
{
var test = _testService.DoSomething();
await Next.Invoke(context);
}
}
public class ValuesController : ApiController
{
private readonly ITestService _testService;
public ValuesController(ITestService testService)
{
_testService = testService;
}
}
Run Code Online (Sandbox Code Playgroud)
整个请求的ITestService实例应该相同.我该如何注册中间件?
这就是我现在这样做的方式:
using (container.BeginExecutionContextScope())
{
var testService = container.GetInstance<ITestService>();
app.Use<TestMiddleware>(testService);
}
Run Code Online (Sandbox Code Playgroud)
这种方法的问题是 - 在注册期间为中间件创建一个ITestService实例并永久保留(如单例),并且对于每个webapi请求,都会在控制器之间创建和共享新实例(webapi范围)
请不要指出这些问题 - WebApi + Simple Injector + OWIN
c# dependency-injection simple-injector asp.net-web-api owin
我们使用WebAPI公开当前的逻辑/业务层.根据我的理解,如果我们想要保护我们的自我免受线程饥饿的请求,我们应该制作Async WebAPI控制器,这样就可以弥补大量的并发请求.
我明白,由于底层服务/业务层是同步的,因此不会有性能提升.我们的目标是大量并发请求通过.
以下是我正在使用的代码:
public async Task<IHttpActionResult> Get()
{
var result = await Task.Run(() => Service.GetAllCompanies()); //existing business layer
return Ok(result);
}
Run Code Online (Sandbox Code Playgroud)
在任务中包装底层图层是很好的继续并实现目标.
iis asynchronous task-parallel-library asp.net-web-api asp.net-web-api2
我们有一个Web应用程序(AngularJS和Web API),它具有非常简单的功能 - 显示作业列表,并允许用户选择和取消选定的作业.
我们正在尝试使用我们的API遵循RESTful方法,但这就是令人困惑的地方.
获得工作很简单 - 很简单 GET: /jobs
我们该如何取消所选择的工作?请记住,这是我们需要实施的唯一作业.对我来说,最简单和最合乎逻辑的方法是将所选作业ID的列表发送到API(服务器)并执行必要的过程.但这不是RESTful方式.
如果我们要按照RESTful方法执行它,那么我们需要发送PATCH请求jobs,json类似于:
PATCH: /jobs
[
{
"op": "replace",
"path": "/jobs/123",
"status": "cancelled"
},
{
"op": "replace",
"path": "/jobs/321",
"status": "cancelled"
},
]
Run Code Online (Sandbox Code Playgroud)
这将需要在客户端生成此json,然后将其映射到服务器上的某个模型,解析"path"属性以获取作业ID,然后执行实际取消.这对我来说似乎非常复杂和虚伪.
关于这种操作的一般建议是什么?当很多操作无法简单地映射到RESTful资源范例时,我很好奇人们在现实生活中做了些什么.
谢谢!
每当我尝试为无状态服务解析端点时,我似乎都会一直收到"未找到服务".我已经尝试使用服务分区解析器和服务代理,但它们都产生相同的结果.是否对Service Fabric有限制,或者我误解了应该如何使用无状态服务?我找不到任何文件说明任何一种方式.
详细说明我试图做的事情.我正在构建一个Api网关.Api网关由RegistryService和RoutingService组成.
我有多个服务结构应用程序,其中一些具有使用WebApi和Owin的"前端"无状态服务.在启动时,这些服务将其路由注册到RegistryService.
Gateway使用Registryservices来确定将请求定向到的服务.此时我正在尝试解决所述服务的端点但未能这样做.但是,如果我将路由更改为有状态后端服务,它可以正常工作.
任何想法都会非常有帮助
c# service asp.net-web-api azure-service-fabric service-fabric-stateful
我正在进行Web API调用,我收到此错误:
405不允许
的方法请求的资源不支持http方法'GET'.
这是电话:
var config = {
url: rootWebApiUrl + '/api/containerMove/allowMultipleBoxesPerMove',
method: 'GET'
};
$http(config)
.then(function (response) {
// code here
}, function (response) {
// code here
});
Run Code Online (Sandbox Code Playgroud)
如果我将HttpGet属性添加到Web API方法,它可以工作:
[HttpGet]
[Route("api/containerMove/allowMultipleBoxesPerMove")]
public bool AllowMultipleBoxesPerMove()
Run Code Online (Sandbox Code Playgroud)
我不明白的是,HttpGet我在同一个Web API控制器上进行的其他调用不需要这样做.这是一个没有HttpGet属性的工作:
var config = {
url: rootWebApiUrl + '/api/containerMove/getBatchRefreshInterval',
method: 'GET'
};
$http(config)
Run Code Online (Sandbox Code Playgroud)
和Web API方法:
[Route("api/containerMove/getBatchRefreshInterval")]
public int GetBatchRefreshInterval()
Run Code Online (Sandbox Code Playgroud)
那么为什么我需要HttpGet一个Web API方法而不是另一个?那些调用和API方法几乎相同.
我正在使用以下技术开发一个小博客应用程序:
在内部我使用MemoryCache类.假设我想让用户能够添加/编辑/删除博客帖子.将包含所有博客文章的JSON保存到缓存中是一个好习惯吗?在现实世界中,会有大量的帖子,因此缓存的序列化/反序列化可能会成为一项昂贵的操作.另外,支持这些项目分页的最佳方法是什么?预先感谢您的帮助.
asp.net-web-api ×10
c# ×7
owin ×3
asp.net ×2
api ×1
asynchronous ×1
if-statement ×1
iis ×1
javascript ×1
json ×1
memorycache ×1
moq ×1
rest ×1
service ×1
unit-testing ×1