标签: asp.net-web-api

如何在OWIN Katana中处理页面未找到错误?

假设我有hotfound.html页面,我想在找不到页面(或wab api方法)时显示它.

如何在OWIN应用程序中处理它?

谢谢

.net http-status-code-404 asp.net-web-api owin katana

1
推荐指数
1
解决办法
1423
查看次数

ASP.Net Core控制器操作会为简单字符串生成内容类型的文本/纯文本

我有以下控制器和操作。

[Route("/api/simple")]
public class SimpleController : Controller
{
    [HttpGet]
    [Route("test")]
    public string Test()
    {
        return "test";
    }
}
Run Code Online (Sandbox Code Playgroud)

当我调用它时,我希望有操作返回"test"(这是有效的JSON),但是它会返回test(不带引号),这是有效的行为还是错误?我想念什么吗?

GET http://localhost:5793/api/simple/test HTTP/1.1
User-Agent: Fiddler
Host: localhost:5793
Accept: application/json


HTTP/1.1 200 OK
Content-Type: text/plain; charset=utf-8
Server: Microsoft-IIS/10.0
X-Powered-By: ASP.NET
Date: Sun, 09 Aug 2015 14:37:45 GMT
Content-Length: 4

test
Run Code Online (Sandbox Code Playgroud)

注意:对于ASP.NET Core 2.0+,当请求中存在Accept标头时,此方法不适用-但是,如果省略了Accept标头并且进行了内容协商,则仍然适用。

asp.net-mvc asp.net-web-api asp.net-core

1
推荐指数
1
解决办法
887
查看次数

通过websockets进行音频流

我将创建语音聊天。我的后端服务器在Node.js上运行,并且客户端与服务器之间的几乎每个连接都使用socket.io。

websocket是否适合我的用例?与P2P相比,我更喜欢通信客户端->服务器->客户端,因为我希望甚至有1000个客户端连接到一个房间。

如果websocket没问题,那么哪种方法最好将AudioBuffer发送到服务器并在其他客户端上回放?我这样做:

navigator.getUserMedia({audio: true}, initializeRecorder, errorCallback);
function initializeRecorder(MediaStream) {
    var audioCtx = new window.AudioContext();
    var sourceNode = audioCtx.createMediaStreamSource(MediaStream);

    var recorder = audioCtx.createScriptProcessor(4096, 1, 1);
    recorder.onaudioprocess = recorderProcess;

    sourceNode.connect(recorder);

    recorder.connect(audioCtx.destination);
}
function recorderProcess(e) {
    var left = e.inputBuffer.getChannelData(0);

    io.socket.post('url', left);
}
Run Code Online (Sandbox Code Playgroud)

但是在接收到其他客户端的数据后,我不知道如何从缓冲区阵列播放此音频流。

编辑

1)为什么如果我不将ScriptProcessor(记录器变量)连接到目标,则不会触发onaudioprocess方法?

文档信息-“尽管您只想可视化一些音频数据,但不必提供目的地” -Web音频概念和用法

2)为什么将记录器变量连接到目标之后,为什么我的扬声器没有听到任何声音,如果我将sourceNode变量直接连接到目标,我可以听到。即使onaudioprocess方法不执行任何操作。

有人可以帮忙吗?

audio-streaming websocket node.js socket.io asp.net-web-api

1
推荐指数
1
解决办法
7890
查看次数

使用用于AzureBearerAuthentication的JWT获取Access令牌

我有一个WebApi应用程序正在使用Windows Azure Active Directory承载身份验证来验证用户.用户通过身份验证后,我想查询Azure的Graph Api以获取有关该用户的更多信息.

我有一个有效的解决方案,但似乎非常hacky.我读取了Authorization标头并删除了承载部分,然后我使用AquireToken获取新标记:

var authHeader = HttpContext.Current.Request.Headers["Authorization"];
var tokenMatch = Regex.Match(authHeader, @"(?<=^\s*bearer\s+).+$", RegexOptions.IgnoreCase);

var result = authInfo.AuthContext.AcquireToken(resourceId, authInfo.Credential, 
    new UserAssertion(tokenMatch.Value));

return result.AccessToken;
Run Code Online (Sandbox Code Playgroud)

必须有一个更好的方法,但我已经尝试过AcquireToken许多不同的重载,这是我能让它工作的唯一方法.我尝试了AcquireTokenSilent,它在我的客户端应用程序中工作,因为TokenCache中有一个令牌,但是当我尝试使用WebApi时,似乎没有任何地方可以实现TokenCache.

authentication jwt asp.net-web-api owin azure-active-directory

1
推荐指数
1
解决办法
1971
查看次数

测试请求是匿名的还是经过身份验证的WebAPI 2 +身份

我正在使用WebAPI 2 + ASP.NET Identity

在我的ApiController方法之一中,我想测试特定的HTTP请求是否来自经过身份验证的客户端(即,该请求是否包含授权标头)。

以下工作,但是也许有更好的方法?

private AuthContext db = new AuthContext();

// GET api/Orders/
[AllowAnonymous]
public async Task<IHttpActionResult> GetOrder(int id)
{
    // ApplicationUser is an IdentityUser.
    ApplicationUser currentUser = null;

    try
    {
        UserManager<ApplicationUser> userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(db));
        currentUser = await userManager.FindByNameAsync(User.Identity.GetUserName());
    }
    catch (Exception)
    {
    }

    if ( currentUser == null )
    {
        // Anonymous request.
        // etc...




    } else {
        // Authorized request.
        // etc...
    }
}
Run Code Online (Sandbox Code Playgroud)

我正在使用默认的路由模板。另一个选择是将两种方法路由到授权请求和匿名请求(用适当的数据注释装饰)。

asp.net-web-api asp.net-web-api-routing asp.net-identity asp.net-web-api2

1
推荐指数
1
解决办法
1499
查看次数

忽略空值-序列化

如何设置System.Runtime.Serialization串行器以忽略空值?

还是我必须为此使用XmlSerializer?如果是这样,怎么办?

(我不希望这样的<ecommerceflags i:nil="true"/>标签被写入,如果它为null,那就跳过它)

c# xml serialization asp.net-web-api

1
推荐指数
1
解决办法
3588
查看次数

HttpContext.Current在等待调用后在异步中为null

HttpContext.Current在等待调用后在异步中为null。

这是我的代码:

if (!string.IsNullOrEmpty(securityGroupName))
{
    // To remove the domain name from the security group name.
    string securityGroupDisplayName = securityGroupName.Split('\\')[1];
    string serviceSecurityGroupId = await this.graphApiClient.GetGroupIdAsync(securityGroupDisplayName).ConfigureAwait(false);

    if (!string.IsNullOrEmpty(serviceSecurityGroupId))
    {
        Task securityGroupRoleAddTask = this.CheckMembershipAndAddRole(serviceSecurityGroupId, userId, securityGroupName);
        Task flightAdminRoleAddTask = this.CheckMembershipAndAddRole(FlightAdminSecurityGroupId, userId, FlightAdminRoleName);
        Task.WaitAll(securityGroupRoleAddTask, flightAdminRoleAddTask);
    }
    else
    {
        LoggingUtilities.Logger.TraceInformation("Azure AD id does not exist for the security group: {0}.", securityGroupName);
        await this.CheckMembershipAndAddRole(FlightAdminSecurityGroupId, userId, FlightAdminRoleName).ConfigureAwait(false);
    }
}
else
{
    LoggingUtilities.Logger.TraceInformation("Security group name is not valid, checking for flight admin role for the user: {0}.", …
Run Code Online (Sandbox Code Playgroud)

c# httpcontext async-await asp.net-web-api

1
推荐指数
1
解决办法
2992
查看次数

自定义Odata v4功能 - 不是有效的odata路由模板 - 未找到该段的资源

我有这样的想法(对自己的行动可能还行)

    [HttpPost]
    [ODataRoute("GenerateFromProduct")]
    public async Task<IHttpActionResult> GenerateFromProduct([FromBodyAttribute] Product product)
    {
        if(!ModelState.IsValid)
        {
            return BadRequest();
        }

        List<string[]> combos = new List<string[]>();
        List<ProductVariant> productVariants = product.GenerateProductVariants();
        db.ProductVariants.AddRange(productVariants);

        await db.SaveChangesAsync();

        return Ok(productVariants);
    }
Run Code Online (Sandbox Code Playgroud)

WebApiConfig中定义的操作可能是这样的:

 builder.EntityType<ProductVariant>().Collection
 .Function("GenerateFromProduct").Returns<List<ProductVariant>>().EntityParameter<Product>("product");
Run Code Online (Sandbox Code Playgroud)

但我不断收到以下错误(几次重写后)

An exception of type 'System.InvalidOperationException' occurred in System.Web.OData.dll but was not handled in user code

Additional information: The path template 'GenerateFromProduct' on the action 'GenerateFromProduct' in controller 'ProductVariants' is not a valid OData path template. Resource not found for the segment 
Run Code Online (Sandbox Code Playgroud)

我有什么想法吗?我没有在网上找到很多关于odata和自定义函数/动作的信息,除了msdn上的信息.

.net asp.net-mvc odata asp.net-web-api odata-v4

1
推荐指数
1
解决办法
6824
查看次数

当您的MVC/Web API从上到下不是异步时会发生什么?

因此,在典型的Web API异步操作中,我们有这样的事情:

[ HttpGet ]
    public async Task<HttpResponseMessage> ReturnSomeStuff() {
        ...
        }
    }
Run Code Online (Sandbox Code Playgroud)

现在,如果我的实际Web API操作不是异步,只是一个普通的方法,但我仍然使用async-things,并且可能只是调用该Result属性Task来返回结果.

如果没有从上到下的整个动作异步,我会错过什么好处?

c# asp.net asp.net-mvc asynchronous asp.net-web-api

1
推荐指数
1
解决办法
149
查看次数

不包含在JSON中时,必需的数字参数默认为0

我有一个模型,我使用DataAnnotations来执行验证,例如

public class OrderDTO
{
    [Required]
    public int Id { get; set; }

    [Required]
    public Decimal Amount { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

然后我检查每个请求中的ModelState以确保JSON有效.

但是,我在Amount上面的数字属性方面遇到了麻烦.即使它被设置为[Required],如果它没有包含在JSON中,它将跳过ModelState验证,因为它自动默认为0而不是null,因此模型看起来有效,即使它不是.

"修复"这个的简单方法是将所有数字属性设置为可为空(int?,Decimal?).如果我这样做,默认为0并不会发生,但我不喜欢这个作为一个明确的解决方案,因为我需要改变我的模型.

有没有办法设置属性,null如果它们不是JSON的一部分?

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

1
推荐指数
1
解决办法
1759
查看次数