我刚刚阅读了有关Web API 模型验证的内容,它有这个示例,但是下面提供的示例代码将无法编译,CreateErrorResponse()因为HttpRequestMessage. 有谁知道为什么?
public class ValidateModelAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(HttpActionContext actionContext)
{
if (actionContext.ModelState.IsValid == false)
{
actionContext.Response = actionContext.Request.CreateErrorResponse(
HttpStatusCode.BadRequest, actionContext.ModelState);
}
}
}
Run Code Online (Sandbox Code Playgroud) 我有一个 Post 方法,根据发布的数据我将返回一个结果。我只想在提供字段时才执行验证。如果没有发布任何值,我不想执行验证。这就是我目前所拥有的。显然,如果该值为空,它将崩溃,因为它需要一个值,我该如何解决这个问题?
public bool IsValidAvailability(int AvailabiltyValue)
{
if (AvailabiltyValue > AvailabilityMax || AvailabiltyValue < AvailabilityMin)
return false;
return true;
}
Run Code Online (Sandbox Code Playgroud)
这是我的验证规则。我可以添加任何内容以使下面的验证仅在提供值时才发生吗?
RuleFor(x => (int)x.Availability).Must(validatorServices.IsValidAvailability).WithMessage("Availability must be between " + validatorServices.AvailabilityMin + " and " + validatorServices.AvailabilityMax);
Run Code Online (Sandbox Code Playgroud) 如果我有一个asyncWeb API 方法,则该Request对象为 null(正如其他帖子(例如这篇文章中讨论的 id ))。
在这种情况下返回响应的最常见方法似乎是使用类似
return new HttpResponseMessage(HttpStatusCode.OK) {
Content = new ObjectContent<T>(myObj, new JsonMediaTypeFormatter())
};
Run Code Online (Sandbox Code Playgroud)
但是格式呢?通常,Request对象会处理该问题,因为它知道请求的内容,但如果我没有对象,Request那么我如何知道请求的格式?
全部,
我正在尝试使用以下源代码对 Dynamics CRM 实施批量请求:
public async Task<HttpResponseMessage> HttpPatchCrmApi(string resource, string data)
{
string uniq = Guid.NewGuid().ToString();
MultipartContent content = new MultipartContent("mixed", "batch_" + uniq);
HttpRequestMessage batchRequest = new HttpRequestMessage(HttpMethod.Post, CrmBaseUrl + "/api/data/v8.0/$batch");
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, CrmBaseUrl + resource);
request.Content = new StringContent(data, Encoding.UTF8, "application/json");
HttpMessageContent query = new HttpMessageContent(request);
content.Add(query);
batchRequest.Content = content;
HttpResponseMessage response = await RbWebApi.SendAsync(batchRequest);
return response;
}
Run Code Online (Sandbox Code Playgroud)
问题是我收到“ 400 Bad request ”
编辑:正如评论中所建议的,这是来自 fiddler 的请求的堆栈跟踪:
POST https://Hidden.api.crm4.dynamics.com/api/data/v8.0/$batch HTTP/1.1
Authorization: Bearer eyJ0eXAiOiJKV.... very long …Run Code Online (Sandbox Code Playgroud) 我发现Controller只需添加以下行即可保护 MVC 应用程序中的所有 MVC
filters.Add(new System.Web.Mvc.AuthorizeAttribute());
Run Code Online (Sandbox Code Playgroud)
到RegisterGlobalFilters。我的 ApiController 仍然需要通过手动添加[Authorize]属性来保护。我是否可以添加类似的行来保护我的所有 WebAPI ApiController?
WebAPI的属性[Authorize]在 中System.Web.Http.AuthorizeAttribute,但我没有成功
filters.Add(new System.Web.Http.AuthorizeAttribute());
Run Code Online (Sandbox Code Playgroud)
这会引发错误
给定的过滤器实例必须实现以下一个或多个过滤器接口:IAuthorizationFilter、IActionFilter、IResultFilter、IExceptionFilter。
我有一个带有 OAuth 登录配置的 WebAPI,如下所示:
app.UseOpenIdConnectAuthentication(
new OpenIdConnectAuthenticationOptions
{
ClientId = clientId,
Authority = authority,
PostLogoutRedirectUri = "https://www.microsoft.com/",
Notifications = new OpenIdConnectAuthenticationNotifications
{
AuthenticationFailed = context =>
{
context.HandleResponse();
context.Response.Redirect("/Error?message=" + context.Exception.Message);
return Task.FromResult(0);
}
}
});
Run Code Online (Sandbox Code Playgroud)
并强制所有控制器使用登录
config.Filters.Add(new System.Web.Http.AuthorizeAttribute());
Run Code Online (Sandbox Code Playgroud)
我现在想添加一个名为 LogoutController 的 ApiController(猜猜它是做什么的)。
我发现我可以使用以下方式从 MVC 注销
System.Web.Security.FormsAuthentication.SignOut();
Run Code Online (Sandbox Code Playgroud)
但我没有以这种方式从 WebAPI 注销。我没有找到任何如何从 WebAPI 注销的信息。但我发现注销过程中可能存在错误,cookie 被保留并必须手动删除,但是代码又是 MVC,似乎我无法进入HttpCookie我的HttpResponseMessage对象:
[HttpGet]
public HttpResponseMessage Logout()
{
FormsAuthentication.SignOut();
// clear authentication cookie
HttpCookie cookie1 = new HttpCookie(FormsAuthentication.FormsCookieName, "");
cookie1.Expires = DateTime.Now.AddYears(-1); …Run Code Online (Sandbox Code Playgroud) 我正在用 C# 编写 ASP.NET Web API 2。我想要的是一个包罗万象的方法,它将针对传入我的 Web API 的每个请求执行。
如果该方法返回 null,则应继续原来的路由,寻找正确的方法。但是,如果该方法返回 HTTPResponseMessage,则服务器应返回该响应,而不继续进行正常路由。
用例是处理可能影响整个 API 的各种场景的能力。例如:禁止单个 IP 地址、阻止(或白名单)某些用户代理、处理 API 调用计数(例如,某人只能向任何人发出 X 请求)API 方法发出 X 个请求)。
我现在能想到的唯一方法就是在我为 API 编写的每个新方法中逐字包含一个方法调用。例如,
[HttpGet]
public HttpResponseMessage myNewMethod()
{
// I want to avoid having to do this in every single method.
var check = methodThatEitherReturnsResponseOrNull(Request);
if (check != null) return (HttpResponseMessage)check;
// The method returned null so we go ahead with normal processing.
...
}
Run Code Online (Sandbox Code Playgroud)
有什么方法可以在路由中实现这一点吗?
我可以从消息正文中读取多个参数吗?
例子 :
public HttpResponseMessage Post([FromBody] int id, [FromBody] string name) { ... }
Run Code Online (Sandbox Code Playgroud) 我正在尝试使用 Newtonsoft Json 转换器序列化一个对象,如下所示:
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using Newtonsoft.Json;
string json = new Newtonsoft.Json.JsonConvert.SerializeObject(new
{
jlpt = "5"
});
Run Code Online (Sandbox Code Playgroud)
但它给了我一个错误说
序列化对象不存在。
但是,当我单击查看参考资料时,我看到了它。
谁能指出我做错了什么?
asp.net-web-api ×10
c# ×8
asp.net ×4
angularjs ×1
asp.net-mvc ×1
asynchronous ×1
cookies ×1
dynamics-crm ×1
json.net ×1
oauth-2.0 ×1
validation ×1
web ×1