我正在ASP.Net Web API中开发REST API.我的API只能通过非基于浏览器的客户端访问.我需要为我的API实现安全性,所以我决定使用基于令牌的身份验证.我对基于令牌的身份验证有一个公平的理解,并阅读了一些教程,但他们都有一些用于登录的用户界面.我不需要任何用于登录的UI,因为登录详细信息将由客户端通过HTTP POST传递,HTTP POST将从我们的数据库授权.如何在API中实现基于令牌的身份验证?请注意 - 我的API将以高频率访问,因此我还必须注意性能.如果我能更好地解释,请告诉我.
.net c# authentication asp.net-web-api http-token-authentication
我面临一个奇怪的问题,几乎花了4个小时没有运气.
我有一个简单的Web API,我在表单提交上调用.
API -
// POST: api/Tool
[HttpPost]
public void Post([FromBody] Object value)
{
_toolService.CreateToolDetail(Convert.ToString(value));
}
Run Code Online (Sandbox Code Playgroud)
HTML的
<!DOCTYPE html>
<html>
<body>
<h2>HTML Forms</h2>
<form name="value" action="https://localhost:44352/api/tool" method="post">
First name:<br>
<input type="text" id="PropertyA" name="PropertyA" value="Some value A">
<br>
Last name:<br>
<input type="text" id="PropertyB" name="PropertyB" value="Some value B">
<br><br>
<!--<input type="file" id="Files" name="Files" multiple="multiple"/>-->
<br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
当我点击提交按钮时,我得到以下错误 -
{"":["The input was not valid."]}
Run Code Online (Sandbox Code Playgroud)
启动课程中的配置 -
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
services.AddSingleton<IConfiguration>(Configuration);
}
public void Configure(IApplicationBuilder …Run Code Online (Sandbox Code Playgroud) 我正在学习async/await,在我读完这篇文章之后不要阻止异步代码
我从@Stephen Cleary的文章中注意到了一个提示.
使用ConfigureAwait(false)来避免死锁是一种危险的做法.您必须对阻塞代码调用的所有方法的传递闭包中的每个等待使用ConfigureAwait(false),包括所有第三方和第二方代码.使用ConfigureAwait(false)来避免死锁充其量只是一个黑客攻击.
它在我上面附上的帖子代码中再次出现.
public async Task<HtmlDocument> LoadPage(Uri address)
{
using (var httpResponse = await new HttpClient().GetAsync(address)
.ConfigureAwait(continueOnCapturedContext: false)) //IO-bound
using (var responseContent = httpResponse.Content)
using (var contentStream = await responseContent.ReadAsStreamAsync()
.ConfigureAwait(continueOnCapturedContext: false)) //IO-bound
return LoadHtmlDocument(contentStream); //CPU-bound
}
Run Code Online (Sandbox Code Playgroud)
据我所知,当我们使用ConfigureAwait(false)时,其余的异步方法将在线程池中运行.为什么我们需要在传递闭包中将它添加到每个等待中?我自己只是认为这是我所知道的正确版本.
public async Task<HtmlDocument> LoadPage(Uri address)
{
using (var httpResponse = await new HttpClient().GetAsync(address)
.ConfigureAwait(continueOnCapturedContext: false)) //IO-bound
using (var responseContent = httpResponse.Content)
using (var contentStream = await responseContent.ReadAsStreamAsync()) //IO-bound
return LoadHtmlDocument(contentStream); //CPU-bound
}
Run Code Online (Sandbox Code Playgroud)
这意味着在使用块中第二次使用ConfigureAwait(false)是没用的.请告诉我正确的方法.提前致谢.
有没有办法暂时禁用或停止特定资源组?我知道我们可以删除资源组,或者我们可以停止资源组下的某些服务,但是我无法找到一种方法可以暂时关闭资源组或其所有资源.
如果我能提供更多关于此的详细信息,请告诉我.
谢谢.
我想将数组作为参数传递给 SqlQuerySpec,以便在为 azure cosmos db 构建查询时能够在 IN 表达式中使用它。我正在尝试做的事情就像我们对常规(字符串、整数等)参数所做的一样:
private SqlQuerySpec BuildQuery(IEnumerable<string> exclTypes)
{
var queryText = "SELECT * FROM root r WHERE r.Type NOT IN (@types)";
var parameters = new SqlParameterCollection{new SqlParameter("@types", exclTypes.ToArray())};
return new SqlQuerySpec()
{QueryText = queryText, Parameters = parameters};
}
Run Code Online (Sandbox Code Playgroud)
但这不会以这种方式工作。我可以通过任何其他方式将数组作为参数传递吗?谢谢。
我正在尝试将 blob 对象解析为 JavaScript 中的 base64 字符串。请帮忙。我的代码是
var reader = new FileReader();
reader.addEventListener("loadend", function () {
// reader.result contains the contents of blob as a typed array
var buffer = reader.result;
var view = new Uint8Array(buffer);
var binary = String.fromCharCode.apply(window, view);
var base64 = btoa(binary);
cb(base64);
console.log(base64);
});
reader.readAsArrayBuffer(data.blob);
Run Code Online (Sandbox Code Playgroud) 我正在尝试将文件上传到.Net Core 2.1中的Azure blob存储。下面是我的代码。
IFormFileCollection files = formCollection.Files;
foreach (var file in files)
{
if (file.Length > 0)
{
_azureCloudStorage.UploadContent(cloudBlobContainer, file.OpenReadStream(), file.FileName);
}
}
Run Code Online (Sandbox Code Playgroud)
UploadContent 实施-
public async void UploadContent(CloudBlobContainer containerReference, Stream contentStream, string blobName)
{
try
{
using (contentStream)
{
var blockBlobRef = containerReference.GetBlockBlobReference(blobName);
//await containerReference.SetPermissionsAsync(new BlobContainerPermissions
//{
// PublicAccess = BlobContainerPublicAccessType.Blob
//});
await blockBlobRef.UploadFromStreamAsync(contentStream);
}
}
catch(Exception ex)
{
//Error here
}
}
Run Code Online (Sandbox Code Playgroud)
代码执行时出现以下错误-
{System.ObjectDisposedException:无法访问关闭的文件。在System.IO.FileStream.get_Position()在Microsoft.AspNetCore.WebUtilities.FileBufferingReadStream.get_Position()在Microsoft.AspNetCore.Http.Internal.ReferenceReadStream.VerifyPosition()在Microsoft.AspNetCore.Http.Internal.ReferenceReadStream.ReadAsync(Byte []缓冲区,位于Microsoft.WindowsAzure.Storage.Core.Util.StreamExtensions.WriteToAsync [T]中的Int32偏移量,Int32计数,CancellationToken CancelToken)(流流,流toStream,IBufferManager bufferManager,Nullable
1 copyLength, Nullable1 maxLength,布尔calculateMd5,ExecutionState1 executionState, StreamDescriptor streamCopyState, …
我有一个 Vue 组件,我试图在其中使用 axios 从 API 获取一些数据。
<template>
<div>
This is Default child component
{{tools[0].name}}
</div>
</template>
<script>
import { CustomJS } from '../js/custom.js';
export default {
name: 'HomeContent',
props: {
tools: []
},
methods: {
fetchData() {
const customJs = new CustomJS();
return customJs.getTools();
}
},
created() {
this.tools = this.fetchData(); //preferably need to wait here wait for response
}
}
</script>
Run Code Online (Sandbox Code Playgroud)
该getTools()函数位于 Vue 组件文件之外的不同 JS 文件中,该文件使用 axios.get 进行 API 调用。
getTools(id = 0){
this.apiTool += (id …Run Code Online (Sandbox Code Playgroud) 我已经在Azure中使用Mongo API创建了一个Cosmos DB数据库。我已经创建了客户端并进行了如下配置-
_mongoDbConnectionString = configuration["MongoDBConnectionString"];
_databaseName = configuration["MongoDBName"];
_client = new MongoClient(_mongoDbConnectionString);
_database = _client.GetDatabase(_databaseName);
_collectionName = configuration["MongoDBCollectionName"];
Run Code Online (Sandbox Code Playgroud)
然后尝试写数据
_database.GetCollection<dynamic>(_collectionName).InsertOne(data);
Run Code Online (Sandbox Code Playgroud)
它因错误而失败-
在使用CompositeServerSelector {Selectors = MongoDB.Driver.MongoClient + AreSessionsSupportedServerSelector,LatencyLimitingServerSelector {AllowedLatencyRange = 00:00:00.0150000}}选择服务器的30000毫秒后发生超时。群集状态的客户端视图为{ClusterId:“ 1”,ConnectionMode:“ ReplicaSet”,类型:“ ReplicaSet”,状态:“ Disconnected”,服务器:[{ServerId:“ {ClusterId:1,端点:”未指定/ botframeworkcosmos。 documents.azure.com:10255“}”,端点:“ Unspecified / botframeworkcosmos.documents.azure.com:10255”,状态:“ Disconnected”,类型:“ Unknown”,HeartbeatException:“ MongoDB.Driver.MongoConnectionException:异常---> System.Net.Internals,打开服务器连接时发生。
我尝试了此解决方案-使用CompositeServerSelector选择服务器30000ms后发生超时,但是它不起作用。
我还尝试过设置这样的SSL策略来配置客户端-
_mongoDbConnectionString = configuration["MongoDBConnectionString"];
_databaseName = configuration["MongoDBName"];
MongoClientSettings settings = MongoClientSettings.FromUrl(
new MongoUrl(_mongoDbConnectionString)
);
settings.SslSettings =
new SslSettings() { EnabledSslProtocols = SslProtocols.Tls12 };
_client = new MongoClient(settings);
_database = _client.GetDatabase(_databaseName);
_collectionName = …Run Code Online (Sandbox Code Playgroud) 以下代码从dateJavaScript 中的对象获取月份。
const date = new Date(dateValue);
const month = date.toLocaleString('default', { month: 'short' });
Run Code Online (Sandbox Code Playgroud)
例如:如果日期是类似的30/07/2019,它将返回Nov.
这在 Chrome 中工作正常,但在 Edge 浏览器中失败并出现错误:
SCRIPT5121:SCRIPT5121:区域设置“默认”格式不正确
我的 Edge 浏览器版本是 41.16299.1004.0
这是一个 jsfiddle:https ://jsfiddle.net/1dwcv9xu/1
根据 MDN,date.toLocaleStringEdge 完全支持:https : //developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleString#Browser_compatibility。
此外,我在 Edge 的 MSDN 文档中找不到此错误代码:https://docs.microsoft.com/en-us/microsoft-edge/devtools-guide/console/error-and-status-codes。
有没有办法解决这个问题或任何替代方法来获取月份的mmm格式?
c# ×6
azure ×3
javascript ×3
asp.net-core ×2
.net ×1
asynchronous ×1
axios ×1
base64 ×1
blob ×1
html ×1
mongodb ×1
sql ×1
vue.js ×1