我知道我可以Url.Link()用来获取特定路由的URL,但是如何在Web API控制器中获取Web API基本URL?
有没有办法将所有枚举显示为swagger中的字符串值而不是int值?
我希望能够提交POST操作并根据其字符串值放置枚举,而不必每次都查看枚举.
我试过,DescribeAllEnumsAsStrings但服务器接收字符串而不是枚举值,这不是我们正在寻找的.
有人解决了这个吗?
编辑:
public class Letter
{
[Required]
public string Content {get; set;}
[Required]
[EnumDataType(typeof(Priority))]
public Priority Priority {get; set;}
}
public class LettersController : ApiController
{
[HttpPost]
public IHttpActionResult SendLetter(Letter letter)
{
// Validation not passing when using DescribeEnumsAsStrings
if (!ModelState.IsValid)
return BadRequest("Not valid")
..
}
// In the documentation for this request I want to see the string values of the enum before submitting: Low, Medium, High. Instead of 0, 1, 2
[HttpGet]
public …Run Code Online (Sandbox Code Playgroud) 我创建了一个WebApi和一个Cordova应用程序.我正在使用HTTP请求在Cordova应用程序和WebAPI之间进行通信.在WebAPI中,我实现了OAuth Bearer Token Generation.
public void ConfigureOAuth(IAppBuilder app)
{
var oAuthServerOptions = new OAuthAuthorizationServerOptions
{
AllowInsecureHttp = true,
TokenEndpointPath = new PathString("/token"),
AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
Provider = new SimpleAuthorizationServerProvider(new UserService(new Repository<User>(new RabbitApiObjectContext()), new EncryptionService()))
};
// Token Generation
app.UseOAuthAuthorizationServer(oAuthServerOptions);
app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
}
Run Code Online (Sandbox Code Playgroud)
这是在SimpleAuthorizationServerProvider实现中
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });
// A little hack. context.UserName contains the email
var user = await _userService.GetUserByEmailAndPassword(context.UserName, context.Password);
if (user == null)
{
context.SetError("invalid_grant", "Wrong email or …Run Code Online (Sandbox Code Playgroud) 我曾经将我的控制器放在Mvc Web Api中的一个单独的类库项目中.我曾经在我的web api项目的global.asax中添加以下行来查找单独项目中的控制器:
ControllerBuilder.Current.DefaultNamespaces.Add("MyClassLibraryProject.Controllers");
Run Code Online (Sandbox Code Playgroud)
除了添加上面的行之外,我从来没有做过任何其他配置.这对我来说一直很好.
但是我无法使用上述方法在WebApi2中执行相同的操作.它只是不起作用.WebApi2项目仍尝试在其自己项目的controllers文件夹中查找控制器.
- 2个月后给予一点摘要更新(因为我开始对此表示赏心悦目):
我创建了一个WebApiOne解决方案,它有2个项目,第一个是WebApi项目,第二个是控制器的类库.如果我将对控制器类库项目的引用添加到WebApi项目中,则所有内容都按预期工作.即如果我去http://mydevdomain.com/api/values我可以看到正确的输出.
我现在创建了一个名为WebApiTwo的第二个项目,它有2个项目,第一个是WebApi2项目,第二个是控制器的类库.如果我将对控制器类库项目的引用添加到WebApi2项目,它将无法按预期工作.即如果我去http://mydevdomain.com/api/values我得到"没有找到匹配名为'值'的控制器的类型."
对于第一个项目,我根本没有做任何自定义设置,我没有:
ControllerBuilder.Current.DefaultNamespaces.Add("MyClassLibraryProject.Controllers");
Run Code Online (Sandbox Code Playgroud)
在我的global.asax中,我没有在他的两篇博文中实现StrathWeb提出的任何自定义解决方案,因为我认为它不再适用; 因为所有工作只是通过将控制器项目的引用添加到WebApi项目.
所以我希望所有人都能为WebApi2工作......但事实并非如此.有没有人真的尝试在WebAPi2中这样做?
在我们的Startup课程中,我配置了以下auth服务器选项:
OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions()
{
AllowInsecureHttp = true,
TokenEndpointPath = new PathString("/api/v1/token"),
AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
Provider = new SimpleAuthorizationServerProvider()
};
Run Code Online (Sandbox Code Playgroud)
在此之后,我们应该使用哪个选项来实际启用承载身份验证?互联网上似乎有两种变体.
选项1:
app.UseOAuthAuthorizationServer(OAuthServerOptions);
app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
Run Code Online (Sandbox Code Playgroud)
选项2:
app.UseOAuthBearerTokens(OAuthServerOptions);
Run Code Online (Sandbox Code Playgroud)
我对它们进行了测试,结果是一样的.
这些选项有什么区别?我们什么时候应该使用哪个?
owin katana asp.net-identity asp.net-web-api2 asp.net-identity-2
我正在使用最新的web api.
我用一些不同的过滤器属性来注释一些控制器.
1 [Authorize]
2 [RessourceOwnerAttribute derived from AuthorizationFilterAttribute]
3 [InvalidModelStateAttribute derived from ActionFilterAttribute]
Run Code Online (Sandbox Code Playgroud)
我无法确定过滤器是按从上到下的顺序运行的.
如何定义执行顺序web api 2.1?
https://aspnetwebstack.codeplex.com/workitem/1065#
我还要为自己解决这个问题吗?
有些人可以帮我了解如何将多个对象从C#控制台应用程序传递到Web API控制器,如下所示?
using (var httpClient = new System.Net.Http.HttpClient())
{
httpClient.BaseAddress = new Uri(ConfigurationManager.AppSettings["Url"]);
httpClient.DefaultRequestHeaders.Accept.Clear();
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var response = httpClient.PutAsync("api/process/StartProcessiong", objectA, objectB);
}
Run Code Online (Sandbox Code Playgroud)
我的Web API方法是这样的:
public void StartProcessiong([FromBody]Content content, [FromBody]Config config)
{
}
Run Code Online (Sandbox Code Playgroud) c# asp.net asp.net-web-api dotnet-httpclient asp.net-web-api2
使用Web API并使用swashbuckle生成swagger文档,我在两个不同的命名空间中定义了两个具有相同名称的不同类.当我在浏览器中打开swagger页面时说
冲突的schemaIds:为类型A和B检测到重复的schemaId.请参阅配置设置 - "UseFullTypeNameInSchemaIds"以获取潜在的解决方法
完整消息:
500:{"消息":"发生了错误.","ExceptionMessage":"冲突的schemaIds:为类型A和B检测到重复的schemaIds.请参阅配置设置 - \"UseFullTypeNameInSchemaIds \"以获取潜在的解决方法","ExceptionType ":"System.InvalidOperationException","StackTrace":"在Swashbuckle.Swagger.SchemaRegistry.CreateRefSchema(类型类型)\ r \n,在Swashbuckle.Swagger.Swagger.SchemaRegistry.CreateInlineSchema(类型类型)\ r \n在Swashbuckle.Swagger. SchemaRegistry.b__1f(JsonProperty prop)\ r \n在System.Linq.Enumerable.ToDictionary [TSource,TKey,TElement](IEnumerable
1 source, Func2 keySelector,Func2 elementSelector, IEqualityComparer1 comparer )\ r \n在Swashbuckle.Swagger.SchemaRegistry.CreateObjectSchema(JsonObjectContract jsonContract) )\ r \n at Swashbuckle.Swagger.SchemaRegistry.CreateDefinitionSchema(Type type)\ r \n at Swashbuckle.Swagger.SchemaRegistry.GetOrRegister(Type type)\ r \n at Swashbuckle.Swagger.SwaggerGenerator.CreateOperation(ApiDescription apiDesc,SchemaRegistry) schemaRegistry)\ r \n在Swashbuckle.Swagger.SwaggerGenerator.CreateP athItem(IEnumerable的1 apiDescriptions, SchemaRegistry schemaRegistry)\r\n at Swashbuckle.Swagger.SwaggerGenerator.<>c__DisplayClass7.<GetSwagger>b__4(IGrouping2组)\ r \n在System.Linq.Enumerable.ToDictionary [TSource,TKEY的,TElement](IEnumerable的1 source, Func2的KeySelector,Func键2 elementSelector, IEqualityComparer1比较器)\ r \n在Swashbuckle.Swagger.SwaggerGenerator.GetSwagger(字符串使用rootUrl,字符串apiVersion)\ r \n在Swashbuckle.Application.SwaggerDocsHandler.SendAsync(HttpRequestMessage请求,CancellationToken cancellationToken)\ r \n在System.Net.Http.MttageInvoker.SendAsync(HttpRequestMessage请求,CancellationToken cancellationToken)\ …
如何在Web Api中生成相同的URL?
var url = Url.Action("Action", "Controller", new { product = product.Id, price = price }, protocol: Request.Url.Scheme);
Run Code Online (Sandbox Code Playgroud)
PS
应该将URL生成为MVC控制器/操作,但是应该从web api中生成.
所以基本上:向我发出一个get请求,api/generateurl然后返回一个url:
http://domain.com/controller/action?product=productId&price=100
Run Code Online (Sandbox Code Playgroud) 这是我在App_Start/WebApiConfig.cs中对Web API的配置:
public static void Register(HttpConfiguration config)
{
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);.....
Run Code Online (Sandbox Code Playgroud)
这是我的global.asax类:
GlobalConfiguration.Configure(WebApiConfig.Register);
Run Code Online (Sandbox Code Playgroud)
但是每当应用程序启动时,我都会遇到以下异常:
路径模板分隔符'/'不能连续出现.它必须由参数或文字值分隔
堆栈跟踪:
at System.Web.Http.Routing.RouteParser.Parse(String routeTemplate)
at System.Web.Http.Routing.DirectRouteFactoryContext.CreateBuilder(String template, IInlineConstraintResolver constraintResolver)
at System.Web.Http.Routing.DirectRouteFactoryContext.CreateBuilderInternal(String template)
at System.Web.Http.Routing.DirectRouteFactoryContext.CreateBuilder(String template)
at System.Web.Http.RouteAttribute.System.Web.Http.Routing.IDirectRouteFactory.CreateRoute(DirectRouteFactoryContext context)
at System.Web.Http.Routing.AttributeRoutingMapper.CreateRouteEntry(String prefix, IDirectRouteFactory factory, IReadOnlyCollection`1 actions, IInlineConstraintResolver constraintResolver, Boolean targetIsAction)
at System.Web.Http.Routing.AttributeRoutingMapper.AddRouteEntries(SubRouteCollection collector, String prefix, IReadOnlyCollection`1 factories, IReadOnlyCollection`1 actions, IInlineConstraintResolver constraintResolver, Boolean targetIsAction)
at System.Web.Http.Routing.AttributeRoutingMapper.AddRouteEntries(SubRouteCollection collector, HttpControllerDescriptor controller, IInlineConstraintResolver …Run Code Online (Sandbox Code Playgroud) asp.net-web-api2 ×10
c# ×8
asp.net ×3
owin ×2
swagger-ui ×2
swashbuckle ×2
.net ×1
base-url ×1
bearer-token ×1
katana ×1
url ×1