小编cra*_*ake的帖子

通过身份验证时从web api控制器操作返回图像

我有一个Web api,它使用带有承载令牌的owin身份验证.我将同时拥有web和wpf(vb)客户端,这些客户端需要在验证时从api请求图像文件.不应在未经身份验证的请求上返回图像.

到目前为止,我有一个工作解决方案,在未经过身份验证时返回图像:

我在c#中的控制器操作:

//[Authorize]
public HttpResponseMessage GetFile()
{
    string localFilePath = "C:/Path/ImageOnServerDisk.png";

    HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
    response.Content = new StreamContent(new FileStream(localFilePath, FileMode.Open, FileAccess.Read));
    response.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
    response.Content.Headers.ContentDisposition.FileName = "myImage.png";
    response.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("image/png");

    return response;
}
Run Code Online (Sandbox Code Playgroud)

这就是我在Web客户端上显示的方式:

<img src="/api/Secure/GetFile" id="img" />
Run Code Online (Sandbox Code Playgroud)

这工作正常,但是当我在上面的操作中取消注释authorize属性时,图像文件没有显示,我收到一条401(未授权)消息,要求GET消息调用GetFile操作.这是因为GET请求中没有访问令牌.

我可以通过ajax使用jQuery来获取,但我不知道如何将结果设置为img元素.

如何在img src中为调用动作的http GET请求设置访问令牌,或者在jQuery中将图像内容设置为img元素?或者有更好的方法来完成这项工作吗?

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

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

在SQL Server中创建ASCII SHA-512哈希

我正在开发一个C#项目,我们有一个文本值放在nvarchar字段的SQL Server数据库表中.使用以下代码对值进行哈希处理:

byte[] data = Encoding.ASCII.GetBytes("valuetohash");
byte[] bytes = new SHA512Managed().ComputeHash(data);
String result = Encoding.ASCII.GetString(bytes);
Run Code Online (Sandbox Code Playgroud)

现在我需要使用T-SQL复制创建相同的值.

谁能告诉我怎么做到这一点?

我试过了 HASHBYTES ( 'SHA2_512', 'valuetohash' )

但是缺少ASCII编码并产生不同的值.

c# t-sql sql-server

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

如何将int数组转换为List <KeyValuePair <int,string >>?

我需要将一个整数数组转换为KeyValuePair列表,其中字符串可以是一个空字符串.这样做有效而优雅的方法是什么?

所以从这个:

int[] ints = new int[] { 1, 2, 3 };
Run Code Online (Sandbox Code Playgroud)

对此:

List<KeyValuePair<int, string>> pairs = new List<KeyValuePair<int, string>>();
pairs.Add(new KeyValuePair<int, string>(1, ""));
pairs.Add(new KeyValuePair<int, string>(2, ""));
pairs.Add(new KeyValuePair<int, string>(3, ""));
Run Code Online (Sandbox Code Playgroud)

显然有很多方法可以做到这一点,从for循环开始,但我最好寻找一行代码,如果可能的话,也许是一个linq语句.

c# linq keyvaluepair

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

通过DateTime属性遍历列表

我有一个List,我需要通过Created计算每天的平均值.如何优雅地迭代列表中显示的每一天的列表?每天可能存在空白,每天都有不同数量的物体.

例如,值可能是这样的:

public class MyObject
{
    public double Value { get; set; }
    public DateTime Created { get; set; }
}

{ Value: 1, Created: 2018-07-01 12:00:00 }
{ Value: 4, Created: 2018-07-01 20:00:00 }
{ Value: 2, Created: 2018-07-03 12:00:00 }
{ Value: 3, Created: 2018-07-04 09:00:00 }
{ Value: 2, Created: 2018-07-04 11:00:00 }
{ Value: 6, Created: 2018-07-04 12:00:00 }
{ Value: 5, Created: 2018-07-06 16:00:00 }
{ Value: 3, Created: 2018-07-06 11:00:00 }
Run Code Online (Sandbox Code Playgroud)

我可以去做这样的事......

List<MyObject> items …
Run Code Online (Sandbox Code Playgroud)

.net c#

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