标签: asp.net-web-api2

如何在Web API控制器中获取基本URL?

我知道我可以Url.Link()用来获取特定路由的URL,但是如何在Web API控制器中获取Web API基本URL?

url base-url asp.net-web-api asp.net-web-api2

68
推荐指数
8
解决办法
12万
查看次数

Swagger UI Web Api文档将枚举显示为字符串?

有没有办法将所有枚举显示为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)

c# asp.net-web-api swagger-ui asp.net-web-api2 swashbuckle

66
推荐指数
17
解决办法
4万
查看次数

使用WebApi中的OAuth Bearer Tokens Generation和Owin将更多信息返回给客户端

我创建了一个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)

c# authentication owin asp.net-web-api2 bearer-token

62
推荐指数
2
解决办法
5万
查看次数

如何配置Web Api 2以在单独的项目中查找控制器?(就像我以前在Web Api中所做的那样)

我曾经将我的控制器放在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中这样做?

c# asp.net-web-api asp.net-web-api2

49
推荐指数
5
解决办法
4万
查看次数

使用OAuthBearerTokens与UseOAuthBearerAuthentication

在我们的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

49
推荐指数
1
解决办法
2万
查看次数

web api中具有多个过滤器的执行顺序

我正在使用最新的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#

http://aspnet.uservoice.com/forums/147201-asp-net-web-api/suggestions/3346720-execution-order-of-mvc4-webapi-action-filters

我还要为自己解决这个问题吗?

c# asp.net action-filter asp.net-web-api asp.net-web-api2

46
推荐指数
2
解决办法
3万
查看次数

将多个复杂对象传递给post/put Web API方法

有些人可以帮我了解如何将多个对象从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

43
推荐指数
4
解决办法
11万
查看次数

swagger错误:schemaIds冲突:为类型A和B检测到重复的schemaIds

使用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,Func 2 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)\ …

c# asp.net-web-api swagger-ui asp.net-web-api2 swashbuckle

43
推荐指数
6
解决办法
2万
查看次数

ASP.NET Web API使用Url.Action生成URL

如何在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)

c# asp.net-mvc-5 asp.net-web-api2

37
推荐指数
1
解决办法
4万
查看次数

路径模板分隔符'/'不能连续出现 - 属性路由问题

配置与错误无关

这是我在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)

.net c# asp.net asp.net-web-api asp.net-web-api2

37
推荐指数
2
解决办法
2万
查看次数